import React, {Component} from 'react'
import {Text, View, Dimensions, TouchableOpacity, Image} from 'react-native'
import Carousel from "react-native-carousel-control";
import StyleUtils from "../res/styles/StyleUtils";
import {IMAGE_URL} from "../httpUtils/IparNetwork";
import IparImageView from "./IparImageView";

const width = Dimensions.get('window').width;


export default class AdvertisementView extends Component {

    constructor(props) {
        super(props);


        this.state = {
            currentPage: 0,
        };
    }

    componentWillUnmount() {
        this.timer && clearInterval(this.timer)
    }

    componentDidMount() {
        let data = this.props.data;

        this.timer = setInterval(
            () => {
                let _index = this.state.currentPage += 1;
                if (_index >= data.length) {
                    _index = 0;
                }
                this.setState({
                    currentPage: _index,
                })
            },
            3000,
        );

    }


    render() {
        let data = this.props.data;

        return <View style={{height: width * 1.14}}>
            {data && <Carousel
                onPageChange={(index) => {
                    this.setState({
                        currentPage: index,
                    })
                }}
                currentPage={this.state.currentPage}
                swipeThreshold={0.1}>
                {data.map((item, index) => {
                    return this._renderItem(item, index)
                })}
            </Carousel>}
        </View>
    }

    /**
     * 广告
     * @param item
     * @param index
     * @returns {*}
     * @private
     */
    _renderItem(item, index) {
        let mainView = <IparImageView
            resizeMode={'cover'}
            errorImage={require('../res/images/ic_image_fail.png')}
            width={'100%'}
            height={'100%'}
            url={item.adver_img}/>;

        return (
            this.state.currentPage === index ? <TouchableOpacity
                    key={index}
                    onPress={() => this.props.onPress(item)}
                    style={[{flex: 1, width: '100%', height: '100%', backgroundColor: '#f1f1f1'}, StyleUtils.center]}>
                    {mainView}
                </TouchableOpacity> :
                <View
                    key={index}
                    style={[{flex: 1, width: '100%', height: '100%', backgroundColor: '#f1f1f1'}, StyleUtils.center]}>
                    {mainView}
                </View>
        );
    }


}